import json
import os

from services.UTG import UTG
from services.PageInfo import *
from services.input_policy import RandomInputPolicy
import utils.mylog as logging

from utils.timmer import run_every_second
from utils.myconfig import *


class InputManager(object):
    """
    输入manager
    -事件获取策略
    -事件执行并获取日志
    -UTG图记录
    """

    # 列举已支持的策略
    INPUT_POLICY = [
        "random"
    ]

    def __init__(self, input_plicy_name, device):
        self.logger = logging.getLogger(self.__class__.__name__)

        self.input_plicy_name = input_plicy_name
        self.device = device
        self.events = []  # 操作序列(Widgets)
        # 记录
        self.UTG = UTG(self.device)

        self.current_page_status = None      # 当前页面状态(本轮操作前)
        self.next_page_status = None         # 下一个页面状态(本轮操作后)
        # 操作生成策略
        self.input_plicy = self.get_input_policy()
        # TODO:日志相关manager

        # 初始化
        self.initialization()

    def initialization(self):
        # TODO:打开指定app
        # 获取当前页面信息及可操作控件list
        self.current_page_status = PageStatus(self.device)
        self.UTG.add_node(self.current_page_status)

    def get_input_policy(self):
        if self.input_plicy_name == "random":
            return RandomInputPolicy(self)

    @run_every_second
    def start(self):
        # 根据策略获取下一步操作widget
        widget = self.input_plicy.get_next_option()
        self.events.append(widget)
        # 操作
        # TODO:增加日志收集及分析
        widget.do(self.device)
        # 操作完成后页面状态记录
        self.next_page_status = PageStatus(self.device)
        # UTG记录
        self.UTG.add_transition(widget, self.current_page_status, self.next_page_status)
        # 将本轮终点设为下一轮起点
        self.current_page_status = self.next_page_status



